<?php
/**
 * Created by PhpStorm.
 * User: chindor
 * Date: 2017/4/21
 * Time: 17:11
 */

namespace app\api\modules\v1\market\controllers;


use app\api\components\ApiController;
use app\api\modules\v1\market\models\Activity_z;
use app\api\modules\v1\market\models\ActivityStatus;
use app\api\modules\v1\market\models\Auth_z;
use app\api\modules\v1\market\models\Log;
use app\api\modules\v1\market\models\Message;
use app\models\base\ActivityLog;
use app\models\base\TodayCost;
use Yii;
use app\api\modules\v1\market\models\BlackBoard;

class ActivityController extends ApiController
{

    public $limit = 30;
    public $child_list_limit = 5;
    public function init()
    {
        parent::init();
    }


    /**活动额搜索
     * project_id
     * @return array
     */
    public function actionSearch_activity()
    {

        $get = \yii::$app->request->get();
        if(empty($get['project_id'])){
            return self::sendMessageJson(Message::MISS_PROJECT_ID);
        }

        $data = Activity_z::search_activity($this->limit);
        if(empty($data)){
            return self::sendMessageJson(Message::EMPTY_DATA);
        }

        $data = ['list'=>Activity_z::format_data_list($data),'page'=>Activity_z::$html_page];

        return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,$data);
    }

    /**  活动的添加
     * @return mixed    返回json信息
     */
    public function actionAdd()
    {
        $post = \yii::$app->request->post();
        $session = \yii::$app->session;

        if(empty($post)){
            if(!empty($_FILES)){
                return self::sendMessageJson(Message::EMPTY_POST);
            }else{
                return self::sendMessageJson(Message::EMPTY_POST);
            }
        }

//        //验证token
        if(!(new Auth_z())->auth($post)){
            return self::sendMessageJson(Message::AUTH_FAIL);
        }

        $validate = \yii\base\DynamicModel::validateData(self::handler_post(['handler_user_id','name','desc','expect_cost','project_id','user_id','all_gold','all_value']),[
            [['user_id'],'required','message'=>Message::EMPTY_USER],
            [['all_value'],'required','message'=>'价值必填'],
            [['all_gold'],'required','message'=>'金币必填'],
            [['project_id'],'required','message'=>'没有选择项目'],
            [['expect_cost'],'required','message'=>'预计消耗不能为空'],
            [['name'],'required','message'=>'活动名不能为空'],
            [['desc'],'required','message'=>'活动描述不能为空'],
//            [['handler_user_id'],'required','message'=>'活动处理人不能为空'],
        ]);


        if($validate -> hasErrors()){
            return self::sendMessageJson(array_values($validate->getFirstErrors())[0]);
            exit;
        }

        $Activity_z = new Activity_z();
        if(!$Activity_z->add($post)){
            return self::sendMessageJson($session->getFlash('error'));
        }

        return self::sendMessageJson(Message::INSERT_SUCCESS,self::$CODE_SUC);

    }

    /**
     *  活动的编辑
     */
    public function actionEdit()
    {
        $post = \yii::$app->request->post();
        $session = \yii::$app->session;

        if(empty($post)){
            if(!empty($_FILES)){
                return self::sendMessageJson(Message::EMPTY_POST);
            }else{
                return self::sendMessageJson(Message::EMPTY_POST);
            }
        }

        //验证token
        if(!(new Auth_z())->auth($post)){
            return self::sendMessageJson(Message::AUTH_FAIL);
        }

        $validate = \yii\base\DynamicModel::validateData(self::handler_post(['activity_id','handler_user_id','name','desc','expect_cost','user_id','all_gold','all_value']),[
            [['user_id'],'required','message'=>Message::EMPTY_USER],
            [['all_value'],'required','message'=>'价值必填'],
            [['all_gold'],'required','message'=>'金币必填'],
            [['expect_cost'],'required','message'=>'预计消耗不能为空'],
            [['name'],'required','message'=>'活动名不能为空'],
            [['desc'],'required','message'=>'活动描述不能为空'],
            [['activity_id'],'required','message'=>'请选择你要编辑的活动'],
//            [['handler_user_id'],'required','message'=>'活动处理人不能为空'],
        ]);

        if($validate -> hasErrors()){
            return self::sendMessageJson(array_values($validate->getFirstErrors())[0]);
            exit;
        }

        $Activity_z = new Activity_z();
        if(!$Activity_z->edit($post)){
            return self::sendMessageJson($session->getFlash('error'));
        }

        return self::sendMessageJson(Message::UPDATE_SUCCESS,self::$CODE_SUC);


    }

    /**
     * @return mixed  活动详情的获取
     */
    public function actionDetail()
    {
        $get = \yii::$app->request->get();

        if(empty($get['activity_id'])){
            return self::sendMessageJson(Message::MISS_ACTIVITY_ID);
        }
        if(empty($get['user_id'])){
            return self::sendMessageJson(Message::MISS_ID);
        }

        //活动详情数据
        $act_detail= Activity_z::get_detail_activity($get);
        $act_detail = empty($act_detail) ? [] : $act_detail;

        //日志详情
        $log = $this->log_list();

        //下属活动列表
        $child_data = $this->child_list();

        if(empty($act_detail)){
            return self::sendMessageJson(Message::EMPTY_ACT_DATA);
        }

        //要显示的按钮列表
        $statusModel = new ActivityStatus();
        $button = $statusModel -> button_list($get['activity_id'],$get['user_id']);

        //要显示的状态值
        $status = $statusModel -> get_status($get['activity_id'],$get['user_id']);

        //按钮详情
        $data = [
            'activity_detail' => $act_detail,
            'child_list'      => $child_data,
            'log'             => $log,
            'status'          => $status, //按钮状态值,
            'button'          => $button  //按钮
        ];

        return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,$data);
    }

    /**
     *   获得日志列表的函数
     * @return  mixed
     */
    public function log_list()
    {
        return Log::formated_list();
    }

    /**日志列表的获取
     * @return mixed
     */
    public function actionLog_list()
    {
        if(!empty($this->log_list())){
            return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,$this->log_list());
        }else{
            return self::sendMessageJson(Message::EMPTY_LOG);
        }

    }

    /**活动的下级活动的获取
     * @return array  返回该活动的下级活动
     */
    private function child_list()
    {
        $get = \yii::$app->request->get();
        if(empty($get['activity_id'])){
            return false;
        }

        //下属活动列表
        $child_data = Activity_z::search_child_activity($this->child_list_limit);
        return ['list'=>Activity_z::format_child_list($child_data),'page'=>Activity_z::$html_page];
    }

    /**活动的下级活动的获取
     * @return array  返回该活动的下级活动
     */
    public function actionChild_list()
    {
        $get = \yii::$app->request->get();
        if(empty($get['activity_id'])){
            return self::sendMessageJson(Message::MISS_ACTIVITY_ID);
        }
        $data = $this->child_list();
        if(empty($data)){
            return self::sendMessageJson(Message::MISS_ACTIVITY_ID);
        }
        return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,$data);
    }

    /**单一项目 详情的获取  右侧仅活动详情
     * @return mixed  json数据
     */
    public function actionSimle_detail()
    {
        $get = \yii::$app->request->get();
        if(empty($get['activity_id'])){
            return self::sendMessageJson(Message::MISS_ACTIVITY_ID);
        }

        if(empty($get['user_id'])){
            return self::sendMessageJson(Message::MISS_ID);
        }

        //活动详情数据
        $act_detail= Activity_z::get_detail_activity($get);
        $act_detail = empty($act_detail) ? [] : $act_detail;

        //要显示的按钮列表
        $statusModel = new ActivityStatus();
        $button = $statusModel -> button_list($get['activity_id'],$get['user_id']);

        //要显示的状态值
        $status = $statusModel -> get_status($get['activity_id'],$get['user_id']);


        //按钮详情
        $data = [
            'activity_detail' => $act_detail,
            'status'          => $status, //按钮状态值,
            'button'          => $button  //按钮
        ];

        return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,$data);
    }
//    public function action
    /**
     * [看板]
     * @return [array] [description]
     */
    public function actionBlackBoard()
    {
        $project_id = Yii::$app->request->get('project_id');
        if(empty($project_id)){
            return parent::sendMessageJson(Message::MISS_PROJECT_ID);
        };
        //未开始
        $act_unbegin = BlackBoard::getActUnbegin($project_id);
        //阻塞中
        $act_block = BlackBoard::getActBlock($project_id);
        //进行中
        $act_process = BlackBoard::getActProcess($project_id);
        //已完成
        $act_complete = BlackBoard::getActComplete($project_id);

        return parent::sendMessageJson(Message::SUCCESS,parent::$CODE_SUC,$data=['unbegin'=>$act_unbegin,'block'=>$act_block,'process'=>$act_process,'complete'=>$act_complete]);
        
    }

    /**
     * @return bool    获得审核通过
     */
    public function actionAudit_pass()
    {
        $post = \yii::$app->request->post();
        $files = $_FILES;
        // var_dump($post);exit;
        $activity_id = \yii::$app->request->post('activity_id');

        //审核人id
        $auditor_id = \yii::$app->request->post('create_user_id');
        $session  = \yii::$app->session;

        $post['user_id'] = \yii::$app->request->post('create_user_id');

        //验证token
        if(!(new Auth_z())->auth($post)){
            return self::sendMessageJson(Message::AUTH_FAIL);
        }

        if(empty($auditor_id)){
            return self::sendMessageJson(Message::MISS_AUDITOR);
        }

        if(empty($activity_id)){
            return self::sendMessageJson(Message::MISS_ACTIVITY);
        }

        //审核活动
        if(empty(Activity_z::audit(1,$activity_id,$auditor_id,$post,$files))){
            return self::sendMessageJson(Message::AUDIT_FAIL.':'.$session->getFlash('error'));
        }

        return self::sendMessageJson(Message::AUDIT_SUCCESS,self::$CODE_SUC);
    }

    /**
     * @return array   填写今日消耗的方法
     */
    public function actionTodayCostInput()
    {
        $post = \yii::$app->request->post();

        //验证token
        if(!(new Auth_z())->auth($post)){
            return self::sendMessageJson(Message::AUTH_FAIL);
        }

        if(empty($post['cost'])){
            return self::sendMessageJson(Message::EMPTY_COST);
        }

        if(!Activity_z::input_tody_cost($post)){
            return self::sendMessageJson(\yii::$app->session->getFlash('error'));
        }

        return self::sendMessageJson(Message::SAVE_COST_SUCCESS,self::$CODE_SUC);
    }

    /**
     *
     *  今日消耗的获取
     */
    public function actionTodayCostGet()
    {
        $get = \yii::$app->request->get();

        if(empty($get['user_id'])){
          return self::sendMessageJson(Message::MISS_ID);
        }

        $todayModel  = TodayCost::findOne(['user_id'=>$get['user_id']]);

        if(empty($todayModel)){
            $todaycost = 0;
        }else{
            $begin_today = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $end_today = $begin_today+24*3600;
            if($todayModel['last_modify'] < $begin_today){
                $todaycost = 0;
            }else{
                $todaycost = $todayModel->all_cost;
            }
        }

        return self::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,['today_cost'=>$todaycost,'today_rest_cost'=>(8-$todaycost)]);
    }

    /**
     * @return array 领取活动的接口
     */
    public function actionReceiveActivity()
    {
        $post = \yii::$app->request->post();
        $post['user_id'] = empty($post['handler_user_id'])?0:$post['handler_user_id'];

        if(!(new Auth_z())->auth($post)){
            return self::sendMessageJson(Message::AUTH_FAIL);
        }

        if(empty($post['activity_id'])){
            return self::sendMessageJson(Message::MISS_ACTIVITY_ID);
        }

        if(!Activity_z::receive_activity($post)){
            return self::sendMessageJson(\yii::$app->session->getFlash('error'));
        }
        return self::sendMessageJson(Message::RECEIVE_SUCCESS,self::$CODE_SUC);
    }

    public static function handler_post($field,$post=false)
    {
        $post = \yii::$app->request->post();
        $arr = [];
        foreach($field as $k => $val){
            $arr[$val] = isset($post[$val])?$post[$val]:'';
        }
        return $arr;
    }
}